package com.voxel.sense.infomsg.module.firm.details.institution.inCrease;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.L;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.RegexUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.utils.constants.RegexConstants;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.IDialog;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.ViewHolder;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.module.map.location.SearchLocationMapActivity;
import com.voxel.sense.infomsg.module.user.audit.DialogAdapter;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.adapter.AbsPickRecyclerAdapter;
import com.voxel.sense.infomsg.widget.adapter.FilterRecyclerSpareAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.IntentConstants;

/**
 * Created by ChenYiYao on 2019/4/1.
 * 增加站位 经度
 */
public class IncreaseBranchActivity extends BViewActivity<IncreaseBranchContract.Presenter> implements IncreaseBranchContract.View {

    private final static String PH_VALUE = "其它";
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.titlebar)
    TextTitleBar titlebar;
    @BindView(R.id.et_id)
    EditText et_id;
    @BindView(R.id.et_firm)
    EditText et_firm;
    //站位类型
    @BindView(R.id.btn_brach_style)
    Button btn_brach_style;
    //站位检测类型
    @BindView(R.id.btn_element_style)
    Button btn_element_style;
    //MN编码
    @BindView(R.id.et_mn_code)
    EditText et_mn_code;
    //坐标系类型
    @BindView(R.id.btn_coord_style)
    Button btn_coord_style;
    @BindView(R.id.et_longitude)
    EditText et_longitude;
    @BindView(R.id.et_latitude)
    EditText et_latitude;
    //定位图标
    @BindView(R.id.ibtn_location)
    ImageButton ibtn_location;
    @BindView(R.id.et_video_his)
    EditText et_video_his;
    @BindView(R.id.et_video_rtmp)
    EditText et_video_rtmp;
    @BindView(R.id.btn_element)
    Button btn_element;
    @BindView(R.id.rv_element)
    RecyclerView rv_element;

    private DialogPlus mDialog;
    private RecyclerView mDialogRecyclerView;
    private DialogAdapter mRcyclerDialogAdapter;
    String mGPSStyle = "";

    private DialogPlus mDialogElement;
    private AbsPickRecyclerAdapter mEletmentMenugAdapter;
    private RecyclerAdapter mEletmentAdapter;


    /**
     * @param firmName  公司名称
     * @param latitude  纬度
     * @param longitude 经度
     */
    public static void show(Context constants, String firmName, double latitude, double longitude) {
        Intent intent = new Intent(constants, IncreaseBranchActivity.class);
        intent.putExtra(IntentConstants.LATITUDE, latitude);
        intent.putExtra(IntentConstants.LONGITUDE, longitude);
        intent.putExtra(IntentConstants.STRING_NAME, firmName);
        constants.startActivity(intent);

    }

    @Override
    protected IncreaseBranchContract.Presenter initPresenter() {
        return new IncreateBranchPresenter(this);
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_increase_branch;
    }


    @Override
    protected void initData() {
        super.initData();
        String name = getIntent().getStringExtra(IntentConstants.STRING_NAME);
        if (!TextUtils.isEmpty(name)) {
            et_firm.setText(name);
        }
        titlebar.setTitleText("添加站位");
        mDialog = createDialog();
        mDialogElement = createEletmentListDialog();

        mEletmentAdapter = new EletmentAdapter();
        initRecycler(rv_element);
        rv_element.setAdapter(mEletmentAdapter);
    }

    @Override
    protected void initEven() {
        super.initEven();
        mRcyclerDialogAdapter.setListener(new RecyclerAdapter.AdapterListenerImpl<ConditionBean>() {
            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, ConditionBean bean) {
                super.onItemClick(holder, bean);
                String type = bean.getType();
                if (IncreaseBranchContract.BRANSH_STYLE.equals(type)) {
                    btn_brach_style.setText(bean.getDesc());
                } else if (IncreaseBranchContract.ELEMENT_STYLE.equals(type)) {

                } else if (IncreaseBranchContract.LOCATION_STYLE.equals(type)) {

                }
                ToastUtil.showToastLong(IncreaseBranchActivity.this, bean.getDesc());
                mDialog.dismiss();
            }
        });

        dialogFootEvent();

        mEletmentAdapter.setListener(new RecyclerAdapter.AdapterListenerImpl<ConditionBean>() {
            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, ConditionBean bean) {
                super.onItemClick(holder, bean);
                removeSelelctedElement(bean);
            }
        });

        mEletmentMenugAdapter.setListener(new RecyclerAdapter.AdapterListenerImpl<ConditionBean>() {
            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, ConditionBean bean) {
                super.onItemClick(holder, bean);
                EditText contentView = mDialogElement.getHeaderView().findViewById(R.id.et_content);

                if (PH_VALUE.equals(bean.getDesc()) && bean.isSelect()) {
                    contentView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
                    contentView.setHint("PH标准值输入格式：6-9，中间“-”不能缺少");
                } else {
                    contentView.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    contentView.setHint("请输入标准值,该值最多3位小数");
                }
            }
        });
    }

    private void dialogFootEvent() {
        View dialogfooterView = mDialogElement.getFooterView();

        dialogfooterView.findViewById(R.id.footer_btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogFootConfirmEvent();
            }
        });
        dialogfooterView.findViewById(R.id.footer_btn_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogElement.dismiss();
            }
        });
    }

    private void dialogFootConfirmEvent() {
        String content = ((EditText) mDialogElement.getHeaderView().findViewById(R.id.et_content)).getText().toString().trim();
        List<ConditionBean> seletedDatas = mEletmentMenugAdapter.getSeletedDatas();

        if (ListUtil.isEmpty(seletedDatas)) {
            showError("请选择添加的元素");
        } else if (TextUtils.isEmpty(content)) {
            showError("请输入正确格式的标准值");
        } else {
            ConditionBean conditionBean = seletedDatas.get(0);
            String desc = conditionBean.getDesc();
            if (PH_VALUE.equals(desc) && !RegexUtils.isMatch(RegexConstants.REGEX_PH_FORMAL_VALUE, content)) {
                //校验ph值不正确
                showError("请输入正确格式的PH标准值,如：6-9，中间“-”不能缺少");
            } else if (!PH_VALUE.equals(desc) && !RegexUtils.isMatch(RegexConstants.REGEX_DECIMALS_SAVE_LAST_THREE, content)) {
                //校验非ph的标准值不正确
                showError("请输入正确格式的标准值,最多输入3位小数");
            } else {
                addBranchElement(conditionBean);
            }
        }
    }

    /**
     * 删除已增加元素
     */
    private void removeSelelctedElement(ConditionBean bean) {
        IDialog.getInstance().showChooseDialog(IncreaseBranchActivity.this, "", "是否要删除" + bean.getDesc() + "元素", new DialogCallBack() {
            @Override
            public void onClick(int what) {
                if (IDialog.YES == what) {
                    mEletmentAdapter.getItems().remove(bean);
                    mEletmentAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    /**
     * 添加元素
     *
     * @param conditionBean
     */
    private void addBranchElement(ConditionBean conditionBean) {
        boolean contains = mEletmentAdapter.getItems().contains(conditionBean);
        String value = ((EditText) mDialogElement.getHeaderView().findViewById(R.id.et_content)).getText().toString().trim();

        if (TextUtils.isEmpty(value)) {
            showError("请填入正确标准值");
        } else if (contains) {
            showError("该元素已添加，不能重复添加");
        } else {
            mEletmentAdapter.add(conditionBean);
            showError(conditionBean.getDesc());
        }
    }

    @OnClick({R.id.btn_brach_style, R.id.btn_element_style, R.id.btn_coord_style,
            R.id.ibtn_location, R.id.btn_element})
    void ViewClickEvent(View v) {
        if (v.getId() == R.id.btn_brach_style) {
            //加载站位类型数据
            mPresenter.doLoadBranchStyleData();
        } else if (v.getId() == R.id.btn_element_style) {
            //加载监测类型的数据
            String s = btn_brach_style.getText().toString();
            if (TextUtils.isEmpty(s)) {
                ToastUtil.showToastLong(this, "请先选择站位类型");
            } else {
                mPresenter.doLoadElementsStyleData();
            }
        } else if (v.getId() == R.id.btn_coord_style) {
            mPresenter.doLocationStyleData();
        } else if (v.getId() == R.id.ibtn_location) {
            double lat = getIntent().getDoubleExtra(IntentConstants.LATITUDE, 0);
            double lon = getIntent().getDoubleExtra(IntentConstants.LONGITUDE, 0);
            SearchLocationMapActivity.show(this, lat, lon);
        } else if (v.getId() == R.id.btn_element) {
            mPresenter.doLoadElementsData();
        }
    }

    private DialogPlus createDialog() {
        return DialogPlus.newDialog(this)
                .setContentHolder(new ViewHolder(creaeteDialog()))
                //                .setContentHolder(new GridHolder(3))
                .setExpanded(true)   //是否完全展开
                .setGravity(Gravity.TOP)
                .setHeader(R.layout.item_dialog_text_header)
                .create();
    }

    private DialogPlus createEletmentListDialog() {
        return DialogPlus.newDialog(this)
                .setContentHolder(new ViewHolder(creaeteEletmentDialog()))
                .setExpanded(false)
                .setGravity(Gravity.TOP)
                .setHeader(R.layout.layout_increase_eletments_dialog_head)
                .setFooter(R.layout.layout_increase_eletments_dialog_foot)
                .create();
    }


    private RecyclerView creaeteDialog() {
        ArrayList arrayList = new ArrayList();
        mRcyclerDialogAdapter = new DialogAdapter();
        mRcyclerDialogAdapter.replace(arrayList);
        mDialogRecyclerView = new RecyclerView(this);
        mDialogRecyclerView.setAdapter(mRcyclerDialogAdapter);
        initRecycler(mDialogRecyclerView);
        return mDialogRecyclerView;
    }


    private RecyclerView creaeteEletmentDialog() {
        ArrayList arrayList = new ArrayList();
        mEletmentMenugAdapter = new FilterRecyclerSpareAdapter();
        mEletmentMenugAdapter.replace(arrayList);
        mEletmentMenugAdapter.setSingleSelect(true);
        RecyclerView recyclerView = new RecyclerView(this);
        recyclerView.setAdapter(mEletmentMenugAdapter);
        initRecycler(recyclerView);
        return recyclerView;
    }


    private void initRecycler(RecyclerView view) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params instanceof ViewGroup.MarginLayoutParams) {
            ((ViewGroup.MarginLayoutParams) params).setMargins(0, 30, 0, 0);
        }
        view.setPadding(0, 10, 0, 0);
//        view.setBackgroundColor(Color.WHITE);
        FlexboxLayoutManager layoutManager = createFlexboxLayout();
        //初始化适配器
        view.setLayoutManager(layoutManager);
        view.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider_10dp_white));

    }

    @NonNull
    private FlexboxLayoutManager createFlexboxLayout() {
        //创建流式布局管理器
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(Factory.app());
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setAlignItems(AlignItems.STRETCH);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        return layoutManager;
    }


    @Override
    public void onShowBranchStyleView(List list) {
        mRcyclerDialogAdapter.replace(list);
        mDialog.show();
    }

    @Override
    public void onShowElementsStyleView(List list) {
        mRcyclerDialogAdapter.replace(list);
        mDialog.show();
    }

    @Override
    public void onShowLocationStyleView(List list) {
        mRcyclerDialogAdapter.replace(list);
        mDialog.show();
    }

    @Override
    public void onShowElementsView(List list) {
        mEletmentMenugAdapter.replace(list);
        mDialogElement.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentConstants.ARC_SEARCH_COORD && resultCode == RESULT_OK) {
            double lon = data.getDoubleExtra(IntentConstants.LONGITUDE, 0);
            double lat = data.getDoubleExtra(IntentConstants.LATITUDE, 0);
            if (lat == 0 && lon == 0) {
                showError("获取坐标失败");
            } else {
                et_latitude.setText(lat + "");
                et_longitude.setText(lon + "");
                btn_coord_style.setText("火星坐标系（高德，GCJ-02）");
                mGPSStyle = IncreaseBranchContract.GPS_GCJ_02;
            }
        }
    }
}
